<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<span>
				<el-select filterable v-model="queryParams.brandName" class="zs-select-md zs-space-right-sm"
					placeholder="品牌名称" clearable>
					<el-option v-for="item in brandDownList" :key="item.brand_id" :label="item.brand_name"
						:value="item.brand_name" />
				</el-select>
				<el-date-picker class="zs-select-md zs-space-right-sm" v-model="queryParams.year" type="year"
					placeholder="日期" :clearable="false" value-format="YYYY" />
				<el-select v-model="queryParams.firstFormat" multiple collapse-tags :teleported="false"
					class="zs-select-md zs-space-right-sm" placeholder="一级业态" clearable>
					<el-option v-for="item in formatList1" :key="item.id" :label="item.brandName" :value="item.id" />
				</el-select>
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid"
							:class="{ 'zs-btn-square-solid-active': queryParams.secondFormat?.length || queryParams.thirdFormat?.length }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-select v-model="queryParams.secondFormat" multiple collapse-tags :teleported="false"
							class="zs-select-md zs-space-right-sm" placeholder="二级业态" clearable>
							<el-option v-for="item in formatList2" :key="item.id" :label="item.brandName"
								:value="item.id" />
						</el-select>
						<el-select v-model="queryParams.thirdFormat" multiple collapse-tags :teleported="false"
							class="zs-select-md zs-space-right-sm" placeholder="三级业态" clearable>
							<el-option v-for="item in formatList3" :key="item.id" :label="item.brandName"
								:value="item.id" />
						</el-select>
					</template>
				</el-popover>
				<el-button @click="getList" class="zs-btn-plain">查询</el-button>
			</span>
			<span>
				<el-button class="zs-btn-plain" @click="handleDownload">
					<el-icon class="el-icon--left">
						<Upload />
					</el-icon>导出
				</el-button>
			</span>
		</div>
		<div class="zs-card zs-table-page-content">
			<hsTableV2 class="db-table-self-tootip" isMultistageHeader :columns="tableData.cloumns" :data="tableData.data"
				fixed :loading="tableData.loading" :multistageHeaderData="multistageData">
			</hsTableV2>
			<div class="zs-text-gray-dark zs-text-sm zs-space-top">*销售额/月租费：万元；月坪效：元/㎡/月；</div>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="queryParams.pageNo" v-model:page-size="queryParams.pageSize"
					:page-sizes="curPageSizes" :small="true" :background="true"
					layout="total, sizes, prev, pager, next, jumper" :total="tableData.total"
					@size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</div>
	</div>
</template>

<script setup lang="jsx">
import { downloadNewFile } from '@/utils/publicUtils';
import { brandFlatEffectDetailNewApi, brandControlApi, getFormatDropDownApi, brandFlatEffectDetailExportApi } from '@/api/Manage/Business/plateauEffectAnalysis'
import { toThousands } from '@/utils/number-util'
import { reactive, ref, computed } from 'vue';
import { useRoute } from 'vue-router';
let route = useRoute();
let { projectCode, firstFormat, secondFormat, thirdFormat, yearMonth, year } = route.query
const curPageSizes = ref([20, 30, 50, 100])

// 查询条件
let queryParams = reactive({
	projectCode: projectCode,
	year: year,
	pageNo: 1,
	pageSize: 30,
	brandName: '',
	firstFormat: firstFormat ? [firstFormat] : [],
	secondFormat: secondFormat ? [secondFormat] : [],
	thirdFormat: thirdFormat ? [thirdFormat] : [],
});
let brandNameStr = computed(() => {
	let str = queryParams.brandName ? queryParams.brandName : '全部'
	return str
});
let formatCodeStr1 = computed(() => {
	let str = queryParams.firstFormat?.length ? queryParams.firstFormat.join(',') : '全部'
	return str
});
let formatCodeStr2 = computed(() => {
	let str = queryParams.secondFormat?.length ? queryParams.secondFormat.join(',') : '全部'
	return str
});
let formatCodeStr3 = computed(() => {
	let str = queryParams.thirdFormat?.length ? queryParams.thirdFormat.join(',') : '全部'
	return str
});
let celWidth = 120
const cloumnsFix = [
	{
		key: "index",
		dataKey: "index",
		title: "序号",
		align: "center",
		width: 60,
		fixed: true,
		cellRenderer: ({ rowIndex }) => (
			rowIndex + 1 + queryParams.pageSize * (queryParams.pageNo - 1)
		)
	},
	{
		key: "floor_name",
		dataKey: "floor_name",
		title: "楼层",
		align: "left",
		fixed: true,
		width: 60,
		cellRenderer: ({ rowData }) => (
			rowData.floor_name
		)
	},
	{
		key: "brand_name",
		dataKey: "brand_name",
		title: "品牌名称",
		align: "left",
		fixed: true,
		width: celWidth,
		cellRenderer: ({ rowData, rowIndex }) => (
			rowData.brand_name && (<div class="db-slef-tooltip">
				<span class="db-tooltip-txt zs-text-ellipsis" style="width: 80px">{rowData.brand_name}</span>
				<div class={{ 'db-tooltip-content-bottom': rowIndex == 0, 'db-tooltip-content-top': rowIndex > 0 }}>{rowData.brand_name}</div>
			</div>)
		)
	},
	{
		key: "user_area",
		dataKey: "user_area",
		title: "租赁面积",
		align: "left",
		fixed: true,
		width: celWidth,
		cellRenderer: ({ rowData }) => (
			rowData.user_area
		)
	},
	{
		key: "firstFormatStr",
		dataKey: "firstFormatStr",
		title: "一级业态",
		align: "left",
		fixed: true,
		width: celWidth,
		cellRenderer: ({ rowData }) => (
			rowData.firstFormatStr
		)
	},
	{
		key: "secondFormatStr",
		dataKey: "secondFormatStr",
		title: "二级业态",
		align: "left",
		fixed: true,
		width: celWidth,
		cellRenderer: ({ rowData }) => (
			rowData.secondFormatStr
		)
	},
	{
		key: "thirdFormatStr",
		dataKey: "thirdFormatStr",
		title: "三级业态",
		align: "left",
		fixed: true,
		width: celWidth,
		cellRenderer: ({ rowData }) => (
			rowData.thirdFormatStr
		)
	},
]
// 表格数据
let tableData = reactive({
	loading: false,
	data: [],
	total: 0,
	cloumns: [],
})
//合并表头
const multistageData = {}
let test = ref(0)
// let indexByENGArr = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
const initMultistageData = (queryTime) => {
	tableData.cloumns = cloumnsFix
	let startIndex = 7 //月份数据列起点索引值
	let keyCount = 4//每组数据字段数
	let num = new Date(queryTime).getMonth() + 1//近6个月的
	// let month = new Date(queryTime).getMonth() + 1 //当前月份
	let year = new Date(queryTime).getFullYear() //当前年

	let windowWidth = document.documentElement.scrollWidth
	let minWidth = (windowWidth - 138 - 60 - 60 - (5 * celWidth)) / (num * 4)
	let width = minWidth < 100 ? 100 : minWidth
	for (let i = num; i > 0; i--) {
		let arr = []
		for (let j = 0; j < keyCount; j++) {
			arr[j] = startIndex
			startIndex++
		}
		multistageData[`multCol_${i}`] = {
			key: `multCol_${i}`,
			title: `${year}年${i}月`,
			childrenIndex: arr
		}
		const groupCol = [
			{
				key: `sales_${i}`,
				dataKey: `sales_${i}`,
				title: "销售额",
				align: "right",
				width: width,
				parentKey: `multCol_${i}`,
				cellRenderer: ({ rowData, rowIndex }) => (
					rowData[`sales_${i}`] && (<div class="db-slef-tooltip">
						<span class="db-tooltip-txt">{toThousands(rowData[`sales_${i}`])}</span>
						<div class={{ 'db-tooltip-content-bottom': rowIndex == 0, 'db-tooltip-content-top': rowIndex > 0 }}>{toThousands(rowData[`sales_yuan_${i}`])}</div>
					</div>)
				)

			},
			{
				key: `spaceEfficiency_${i}`,
				dataKey: `spaceEfficiency_${i}`,
				title: "月坪效",
				align: "right",
				width: width,
				parentKey: `multCol_${i}`,
				headerCellRenderer: () => (
					<>
						月坪效
						<el-popover placement="bottom" width="280" trigger="hover">
							{{
								reference: () => <i class="icon-i zs-text-gray zs-space-left-min"></i>,
								default: () => <div v-html={'（销售额/经营天数*30）/月末起租面积'}></div>
							}}
						</el-popover>
					</>
				),
				cellRenderer: ({ rowData }) => (
					toThousands(rowData[`spaceEfficiency_${i}`])
				)
			},
			{
				key: `invrecamtl_${i}`,
				dataKey: `invrecamtl_${i}`,
				title: "月租费",
				align: "right",
				width: width,
				parentKey: `multCol_${i}`,
				cellRenderer: ({ rowData, rowIndex }) => (
					rowData[`invrecamtl_${i}`] && (<div class="db-slef-tooltip">
						<span class="db-tooltip-txt">{toThousands(rowData[`invrecamtl_${i}`])}</span>
						<div class={{ 'db-tooltip-content-bottom': rowIndex == 0, 'db-tooltip-content-top': rowIndex > 0 }}>{toThousands(rowData[`invrecamtl_yuan_${i}`])}</div>
					</div>)
				)
			},
			{
				key: `rentalSalesRatio_${i}`,
				dataKey: `rentalSalesRatio_${i}`,
				title: "租售比",
				align: "right",
				width: width,
				parentKey: `multCol_${i}`,
				headerCellRenderer: () => (
					<>
						租售比
						<el-popover placement="bottom" width="120" trigger="hover">
							{{
								reference: () => <i class="icon-i zs-text-gray zs-space-left-min"></i>,
								default: () => <div v-html={'月租费/销售额'}></div>
							}}
						</el-popover>
					</>
				),
				cellRenderer: ({ rowData }) => (
					rowData[`rentalSalesRatio_${i}`]
				)
			},
		]
		tableData.cloumns = tableData.cloumns.concat(groupCol)
	}
}
async function getList() {
	test.value++
	tableData.loading = true;
	let params = Object.assign({}, queryParams);
	params.firstFormat = formatCodeStr1.value
	params.secondFormat = formatCodeStr2.value
	params.thirdFormat = formatCodeStr3.value
	params.brandName = brandNameStr.value
	let res = await brandFlatEffectDetailNewApi(params);
	let resData = res.data;
	if (resData.errorCode == 200 && resData.data) {
		const selectYearMonth = Number(queryParams.year) < Number(yearMonth.split('-')[0]) ? `${queryParams.year}-12` :
			Number(queryParams.year) == Number(yearMonth.split('-')[0]) ? yearMonth :
				Number(queryParams.year) > Number(yearMonth.split('-')[0]) ? `${queryParams.year}-12` : ''
		initMultistageData(selectYearMonth)
		tableData.data = resData.data;
		tableData.total = resData.totalCount;
	} else {
		tableData.data = [];
		tableData.total = 0;
	}
	tableData.loading = false;
}
// 分页
const handleSizeChange = (val) => {
	queryParams.pageSize = val
	getList()
}
const handleCurrentChange = (val) => {
	queryParams.pageNo = val
	getList()
}
let brandDownList = ref([]);
let formatList1 = ref([]);
let formatList2 = ref([]);
let formatList3 = ref([]);
const getOptionList = async () => {
	//业态下拉
	let res1 = await getFormatDropDownApi({ brandType: 'WIN_BIZ_TYPE_LEVEL_1' })
	if (res1.data.errorCode == 200) {
		formatList1.value = res1.data.data
	}
	let res2 = await getFormatDropDownApi({ brandType: 'WIN_BIZ_TYPE_LEVEL_2' })
	if (res1.data.errorCode == 200) {
		formatList2.value = res2.data.data
	}
	let res3 = await getFormatDropDownApi({ brandType: 'WIN_BIZ_TYPE_LEVEL_3' })
	if (res1.data.errorCode == 200) {
		formatList3.value = res3.data.data
	}
	// 品牌
	let res4 = await brandControlApi({ yearmonth: yearMonth, projectCode })
	if (res4.data.code == 200) {
		brandDownList.value = res4.data.data;
	}
	getList()
}
getOptionList()

//导出
const handleDownload = async () => {
	const fileName = `品牌坪效分析报表明细.xls`;
	let fileData;
	let params = Object.assign({}, queryParams);
	params.firstFormat = formatCodeStr1.value
	params.secondFormat = formatCodeStr2.value
	params.thirdFormat = formatCodeStr3.value
	params.brandName = brandNameStr.value
	await brandFlatEffectDetailExportApi(params).then(res => {
		fileData = res.data;
	});
	downloadNewFile(fileData, fileName);
};
</script>
